﻿using System;
using System.Collections;
using NHibernate;
using NHibernate.Cfg;
using System.Collections.Generic;

namespace Business
{
    public class UsersGroup
    {
        private ISessionFactory _sessionFactory;
        public UsersGroup()
        {
            _sessionFactory = DataObjects.Service.SessionFactory.GetInstance().GetNHibernateFactory();
        }
        
        public ArrayList List()
        {
            ArrayList arrRet = new ArrayList();
            using (ISession session = _sessionFactory.OpenSession())
            using (ITransaction tx = session.BeginTransaction())
            {
                arrRet = (ArrayList)session.CreateCriteria(typeof(DataObjects.UsersGroup)).List();
                tx.Commit();
            }
            return arrRet;
        }

        public DataObjects.UsersGroup GetObjectByPK(string grpId)
        {
            ArrayList arrTemp = new ArrayList();
            using (ISession session = _sessionFactory.OpenSession())
            using (ITransaction tx = session.BeginTransaction())
            {
                IQuery query = session.CreateSQLQuery("select top 1 * from USERS_GROUP where Group_ID =?").AddEntity(typeof(DataObjects.UsersGroup));
                query.SetString(0, grpId);
                arrTemp = (ArrayList)query.List();
                tx.Commit();

                if (arrTemp.Count > 0)
                {
                    return (DataObjects.UsersGroup)arrTemp[0];
                }
                return null;
            }
        }

        //code insert - update - delete 
        public void Insert(DataObjects.UsersGroup oGroupUser)
        {
            using (ISession session = _sessionFactory.OpenSession())
            using (ITransaction tx = session.BeginTransaction())
            {
                session.Save(oGroupUser);
                tx.Commit();			        
            }
        }
        public void Update(DataObjects.UsersGroup oGroupUser)
        {
            using (ISession session = _sessionFactory.OpenSession())
            using (ITransaction tx = session.BeginTransaction())
            {
                session.Update(oGroupUser);
                tx.Commit();		        
            }
        }
        public void DeleteByPK(string grpId)
        {
            using (ISession session = _sessionFactory.OpenSession())
            using (ITransaction tx = session.BeginTransaction())
            {
                DataObjects.UsersGroup oGroupUser = (DataObjects.UsersGroup)session.Load(typeof(DataObjects.UsersGroup), grpId);
                session.Delete(oGroupUser);
                tx.Commit();
            }
        }
    }
}
